import ResItem from "./ResItem";

export class ResCache {
    protected resCache: { [k: string]: ResItem } = {}

    add(key: string, res: ResItem) {
        this.resCache[key] = res;
    }

    get(key: string) {
        return this.resCache[key]
    }

    has(key: string) {
        return !!this.resCache[key]
    }

    remove(key: string) {
        delete this.resCache[key]
    }


    /**
    * 删除所有资源
    */
    release() {

        let resources: string[] = Object.keys(this.resCache);
        for (let index = 0; index < resources.length; index++) {
            const key = resources[index];
            const element: ResItem = this.resCache[key];
            if (element) {
                element.release();
                delete this.resCache[key];
            } else {
                // console.warn("ResLoader release url  =  is error  ",key)
            }
        }

        // this.helper.clear()

    }

    releaseUnusedAssets() {
        let resources: string[] = Object.keys(this.resCache);
        for (let index = 0; index < resources.length; index++) {
            const key = resources[index];
            const element: ResItem = this.resCache[key];
            if (element && element.getUseCount() == 0) {
                delete this.resCache[key];
            }
        }
        // ResHelper.releaseUnusedAssets()

    }
}